/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bdd;

import beans.Article;
import beans.ListeArticle;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author maboisba
 */
public class Connexion {

  private Properties properties;
  private Connection connection;
  private PreparedStatement pst;
  private ResultSet rs;
  private String url;

  public Connexion() {
    super();
  }
  
  public Connexion(String url) {
    super();
    this.url = url;
  }
  
  public void connexion() throws IOException{

    
    try {
      properties = new Properties();
      FileInputStream in = new FileInputStream(url);
      properties.load(in);
    }
    catch (FileNotFoundException ex) {
      Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
      Class.forName(properties.getProperty("driver"));
      //Class.forName("com.mysql.jdbc.Driver");
    }
    catch (ClassNotFoundException ex) {
      System.err.println("Erreur de chargement du driver.");
    }
    
    try {
      connection = DriverManager.getConnection(properties.getProperty("adresse_bd"), properties.getProperty("user"), properties.getProperty("pwd"));
    }
    catch (SQLException ex) {
      System.err.println("Erreur de connexion à la base de données.");
    }
  }

  public ListeArticle getArticles(){
    ListeArticle articles = new ListeArticle();
    String request = "SELECT * FROM Articles";

    try {
      
      pst = connection.prepareStatement(request);
      rs = pst.executeQuery();

      while(rs.next()) {
        System.out.println("ARTICLE !!");
        Article article = new Article();
        article.setId(rs.getInt("id"));
        article.setNom(rs.getString("nom"));
        article.setDescription(rs.getString("description"));
        article.setPrix(rs.getFloat("prix"));
        System.out.println(article.getId());
        System.out.println(article.getNom());
        System.out.println(article.getDescription());
        System.out.println(article.getPrix());
        articles.add(article);
      }
    }
    catch (SQLException ex) {
      System.err.println("Erreur de requête SQL.");
    }
    
    return articles;
  }

  public void deconnexion(){
    try {
      rs.close();
      pst.close();
      connection.close();
    }
    catch (SQLException ex) {
      Logger.getLogger(Connexion.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

}
